/**
 * Created by user on 2015/12/24.
 */

var scoreShopService = require('../../../services/mis/master/scoreShopService');
var messageUtil = require('../../../common/utils/messageUtil');
var toolUtil = require('../../../common/utils/toolUtil');
var mysqlUtil = require('../../../common/utils/mysqlUtil');

exports.scoreShopList = function(req, res) {

    scoreShopService.scoreShopListService(req, function (err, results) {

        if (err) {
            logger.error('Exception happen when scoreShopList...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when scoreShopList...'));
        } else {
            var data={};
            var data = {
                count: results[0]["count"],
                totalPage: results[0]["totalPage"],
                list: results[1]
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));

        }

    });
};

exports.scoreShopAddUpdate = function(req, res){
    var input = req.body;

    toolUtil.uploadImageService(null, null, req, function (err, images) {
        if (err) {
            res.json(messageUtil.composeFailedMessage(req, 'Failed to upload Images... - ' + err.message));
        } else {
            var data = new Array();

            images.forEach(function (image) {
                if (image != null) {
                    data.push(image);
                }
            });

            input.inventoryLevel = Number(input.inventoryLevel);
            input.price = Number(input.price);
            input.cId = Number(input.cId);
            input.images = data[0];
            input.status = 0;
            //input.__type__ = 'com.neighborhoods.data.domain.score.ScoreShopEntity';
            logger.info(input);

            var ctime = Math.round(new Date().getTime()),sql;
            if(input.cId){
                sql = "UPDATE score_shop SET product_name = '"+ input.productName +"',product_desc = '"+ input.productDesc +"',inventory_level = '"+ input.inventoryLevel +"',price = '"+ input.price +"'"+ (input.images == undefined?"":",images = '"+input.images+"'")+",update_time = '"+ ctime +"' WHERE id = '"+input.cId+"'";
            }else{
                sql = "insert into score_shop (product_name,product_desc,inventory_level,price,images,status,create_time) values ('"+input.productName+"','"+input.productDesc+"','"+input.inventoryLevel+"','"+input.price+"','"+input.images+"','"+input.status+"','"+ ctime +"')";
            }
            logger.info(sql);
            mysqlUtil.query(sql, function (err, result) {
                if (err) {
                    logger.error('Exception happened when changeStatus...!' + err.message);
                    res.json(messageUtil.composeFailedMessage(req, 'Exception happened when addOneGoods...!' + err.message));
                } else {
                    res.json(messageUtil.composeSucceededMessage(req, null, null));
                }
            });

        }
    })
};